﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using QMSDAL;

namespace QuaManSys.OuterInfo
{
    public partial class OuterInfoProcess : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CurUser"] == null)
            {
                Response.Redirect("~/Login.aspx");
            }
            lblQuaInfoProNo.Text = Request.QueryString["id"]; //修改为查询字符串
            fdbktime.Attributes.Add("ReadOnly", "True");
            lblCusRT.Attributes.Add("ReadOnly", "True");
            txtProDL.Attributes.Add("ReadOnly", "True");
            txtKeyWords.Attributes.Add("ReadOnly", "True");

            if (!IsPostBack)
            {
                initddlProNo();
                initResponDept();
                initRelatedDept();
                txtProCmm.Attributes.Add("enabled", "false");
                txtReqRsl.Attributes.Add("enabled", "false");
                if (Request["close"].ToString().Equals("1"))
                {
                    finish.Text = "闭环";  //close==1表示该页面为闭环页面
                    pnlLoadin.Visible = false;
                    Panel1.Visible = false;
                    Panel2.Visible = false;
                    txtReqRsl.Attributes.Remove("enabled");
                    txtProCmm.Attributes.Remove("enabled");
                    lnkInsert.Visible = false;
                }
                if (Request["close"].ToString().Equals("2"))
                {
                    finish.Text = "归档";  //close==2表示该页面为归档页面
                    pnlLoadin.Visible = false;
                    Panel1.Visible = false;
                    Panel2.Visible = false;
                    txtReqRsl.Attributes.Remove("enabled");
                    txtProCmm.Attributes.Remove("enabled");
                    lnkInsert.Visible = false;
                }
                if (Request["close"].ToString().Equals("5"))//close=5表示页面为评价页面
                {
                    finish.Text = "评价";
                    pnlLoadin.Visible = false;
                    Panel1.Visible = false;
                    Panel2.Visible = false;
                    txtProCmm.Attributes.Remove("enabled");
                    txtReqRsl.Attributes.Remove("enabled");
                    lnkInsert.Visible = false;
                }
                initQuaInfoTextBox();
                initDepartTextBox();
                initFeedBackTextBox();
                initAttatchment();

            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            initProcessTable();
        }
        #region display

        /// <summary>
        /// 初始化质量信息处理表
        /// </summary>
        private void initProcessTable()
        {
            CurUser ps = (CurUser)Session["CurUser"];
            txtProDept.ReadOnly = true;
            txtProName.ReadOnly = true;
            txtProDept.Text = ps.department;
            txtProName.Text = ps.name;
        }

        /// <summary>
        /// 把外部质量信息表中的数据显示出来
        /// </summary>
        private void initQuaInfoTextBox()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                var qualityInfo = from c in context.OuterQualityInfo
                                  where c.qualityInfoId == lblQuaInfoProNo.Text
                                  select c;

                txtImpLev.Text = qualityInfo.Single().levelOfImportance;
                ddlProNo.Text = qualityInfo.Single().projectNo;
                txtlblMacTyp.Text = GCBH.GetJXGCBH(ddlProNo.Text);
                txtlblMacNo.Text = GCBH.GetTFGCBH(ddlProNo.Text);
                txtComponent.Text = qualityInfo.Single().components;
                txtFaiTyp.Text = qualityInfo.Single().faultType;
                txtManufac.Text = qualityInfo.Single().producer;
                txtPjCls.Text = qualityInfo.Single().projectCategory;
                txtPjNam.Text = qualityInfo.Single().name;
                txtInfoDsc.Text = qualityInfo.Single().description;
                InfoCls.SelectedIndex = Convert.ToInt16(qualityInfo.Single().informationCategory);
                txtReqAdv.Text = qualityInfo.Single().recommendedTreatPlan;
                txtReqRsl.Text = qualityInfo.Single().processingResults;
                txtProCmm.Text = qualityInfo.Single().processingAssess;
                txtProDL.Text = qualityInfo.Single().deadline.ToString().Split(' ')[0].Replace('-', '/');
                txtSearch.Text = qualityInfo.Single().informationSource;
            }
        }

        /// <summary>
        /// 把责任部门和关注部门显示出来
        /// </summary>
        private void initDepartTextBox()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                var dept = from c in context.OuterResponsibleDepart
                           where c.qualityInfoId == lblQuaInfoProNo.Text
                           select c;
                string deptString = "";
                foreach (var item in dept)
                {
                    if (item.isResponDepart == 0)
                    {
                        if (deptString == "") deptString += item.department;
                        else deptString += "|" + item.department;
                    }
                    else
                    {
                        ResponDept.Text = item.department;
                    }
                }
                txtKeyWords.Text = deptString;
            }
        }

        /// <summary>
        /// 显示反馈表中的数据
        /// </summary>
        private void initFeedBackTextBox()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                var fbset = from c in context.OuterQualityInfoFeedback
                            where c.qualityInfoId == lblQuaInfoProNo.Text
                            select c;
                lblFdCom.Text = fbset.Single().feedbackUnit;
                txtFdPer.Text = fbset.Single().feedbackName;
                fdbktime.Text = fbset.Single().feedbackTime.ToString().Split(' ')[0].Replace('-', '/');
                ProcssComd.SelectedIndex = Convert.ToInt16(fbset.Single().processingDemands);
                lblCusCo.Text = fbset.Single().customerCompany;
                lblRelCo.Text = fbset.Single().relatedParty;
                lblCusNam.Text = fbset.Single().customerName;
                lblCusRol.Text = fbset.Single().customerRole;
                lblCusTel.Text = fbset.Single().customerPhone;
                lblCusRT.Text = fbset.Single().customerReqCloTime.ToString().Split(' ')[0].Replace('-', '/');
                CareLevel.SelectedIndex = Convert.ToInt16(fbset.Single().customerAttitude);
                TextBox4.Text = fbset.Single().cusomerOtherInfo;
                TextBox2.Text = fbset.Single().qualityInfoDes;
                TextBox3.Text = fbset.Single().solutionProposal;

                string s = fbset.Single().subsequentRequest;
                if (s.Length == 1)
                {
                    CustmReq.SelectedIndex = Convert.ToInt16(s);
                }
                else
                {
                    CustmReq.SelectedIndex = 3;
                    instruction.Text = s.Substring(2);
                }


            }
        }
        #endregion


        /*
         * multiView的下一步
         */
        protected void nextstep_Click(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 1;
        }

        /*
         * multiView的上一步
         */
        protected void prestep_Click(object sender, EventArgs e)
        {
            ////从session中取出当前用户信息并显示
            //CurUser user = (CurUser)Session["CurUser"];
            ////判断当前用户是否具有归档权限
            //bool roleAccess = Permission.JudgePermission(user, "1B", "D1");
            MultiView1.ActiveViewIndex = 0;
        }

        #region

        /// <summary>
        /// 初始化工程编号下拉框
        /// </summary>
        private void initddlProNo()
        {
            DataSet myDs = GCBH.GetAllProjectNumbers();
            foreach (DataTable dt in myDs.Tables)
            {
                int count = 0;
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                    {
                        ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                        ddlProNo.Items.Insert(count++, li);
                    }
                }
            }
            txtlblMacTyp.Text = GCBH.GetJXGCBH(ddlProNo.Text);
            txtlblMacNo.Text = GCBH.GetTFGCBH(ddlProNo.Text);
        }



        /// <summary>
        /// 初始化责任部门下拉框选项
        /// </summary>
        private void initResponDept()
        {
            DataSet ds = Department.GetAllDept();
            foreach (DataTable dt in ds.Tables)
            {
                ResponDept.Items.Clear();
                int count = 0;
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                    {
                        //if (dt.Rows[curRow][curCol].ToString() == ResponDept.Text) continue;
                        ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                        ResponDept.Items.Insert(count++, li);
                    }
                }
            } 
        }

        /// <summary>
        /// 初始化关注部门复选框选项
        /// </summary>
        private void initRelatedDept()
        {
            DataSet ds = Department.GetAllDept();
            foreach (DataTable dt in ds.Tables)
            {
                ResponDept.Items.Clear();
                int count = 0;
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                    {
                        if (dt.Rows[curRow][curCol].ToString() == ResponDept.Text) continue;
                        ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                        ResponDept.Items.Insert(count++, li);
                    }
                }
            } 
            
        }

        #endregion

        bool isValidate()
        {
            if (fdbktime.Text == "") return false;
            if (lblCusRT.Text == "") return false;
            if (txtProDL.Text == "") return false;
            return true;
        }

        /// <summary>
        /// 插入处理数据
        /// </summary>
        protected void InsertProinfo(object sender, EventArgs e)
        {
            using (var db = new QuaManSysEntities())
            {
                OuterQualityInfoPro Insertinfo = new OuterQualityInfoPro
                {
                    processerDepart = txtProDept.Text,
                    processerName = txtProName.Text,
                    processingDate = Convert.ToDateTime(txtProDate.Text),
                    opinion = txtProOpn.Text,
                    qualityInfoId = lblQuaInfoProNo.Text

                };

                db.OuterQualityInfoPro.Add(Insertinfo);
                db.SaveChanges();
                txtProDate.Text = "";
                txtProOpn.Text = "";
            }

            Repeater1.DataSourceID = "EntityProcess";
            Repeater1.DataBind();
        }

        protected void ResponDept_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataSet ds = Department.GetAllDept();
            foreach (DataTable dt in ds.Tables)
            {
                txtKeyWords.Text = "";
                cblKeyWords.Items.Clear();
                int count = 0;
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                    {
                        if (dt.Rows[curRow][curCol].ToString() == ResponDept.Text) continue;
                        if (!dt.Rows[curRow][curCol].ToString().Equals(ResponDept.Text))
                        {
                            ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                            cblKeyWords.Items.Insert(count++, li);
                        }                       
                    }
                }
            } 
        }

        protected void finish_Click(object sender, EventArgs e)
        {
            //从session中取出当前用户信息并显示
            CurUser user = (CurUser)Session["CurUser"];
            if (Request["close"].ToString().Equals("1"))  //闭环确认
            {
                //判断当前用户是否具有归档权限
                bool roleAccess = Permission.JudgePermission(user, "2B", "D0");
                if (roleAccess)
                {
                    using (QuaManSysEntities context = new QuaManSysEntities())
                    {
                        var query = context.OuterQualityInfo.Find(lblQuaInfoProNo.Text);
                        query.processingStatus = "闭环";
                        query.processingAssess = txtProCmm.Text;
                        query.processingResults = txtReqRsl.Text;
                        context.SaveChanges();
                        Response.Redirect("SubmitSuccess.aspx");
                    }
                }
            }
            else if (Request["close"].ToString().Equals("2"))  //归档确认
            {
                //判断当前用户是否具有归档权限
                bool roleAccess = Permission.JudgePermission(user, "2B", "D1");
                if (roleAccess)
                {
                    using (QuaManSysEntities context = new QuaManSysEntities())
                    {
                        var query = context.OuterQualityInfo.Find(lblQuaInfoProNo.Text);
                        query.processingStatus = "归档";
                        query.processingAssess = txtProCmm.Text;
                        query.processingResults = txtReqRsl.Text;
                        context.SaveChanges();
                        Response.Redirect("SubmitSuccess.aspx");
                    }
                }
            }
            else if (Request["close"].ToString().Equals("5"))
            {
                //判断当前用户是否具有归档权限
                bool roleAccessA = Permission.JudgePermission(user, "2B", "A");
                bool roleAccessB = Permission.JudgePermission(user, "2B", "D1");
                if (roleAccessA || roleAccessB)
                {
                    using (QuaManSysEntities context = new QuaManSysEntities())
                    {
                        var query = context.OuterQualityInfo.Find(lblQuaInfoProNo.Text);
                        query.processingStatus = "评价";
                        query.processingAssess = txtProCmm.Text;
                        query.processingResults = txtReqRsl.Text;
                        context.SaveChanges();
                        Response.Redirect("SubmitSuccess.aspx");
                    }
                }
            }
            else
            {
                //判断当前用户是否具有归档权限
                bool roleAccess = Permission.JudgePermission(user, "2B", "B1");
                if (roleAccess)
                {
                    fileUpload();
                    using (QuaManSysEntities context = new QuaManSysEntities())
                    {
                        string infoCategory = InfoCls.SelectedIndex.ToString();
                        var query = context.OuterQualityInfo.Find(lblQuaInfoProNo.Text);
                        query.processingResults = txtReqRsl.Text;
                        query.processingAssess = txtProCmm.Text;
                        context.SaveChanges();
                        //CurUser user = (CurUser)Session["CurUser"];
                        var process = (from d in context.OuterResponsibleDepart.
                                     Where(no => no.qualityInfoId.Equals(lblQuaInfoProNo.Text)).
                                     Where(ps => ps.department.Equals(user.department))
                                       select d);
                        process.Single().processed = 1;
                        Common.OuterRelatedDeptOperation.AddOuterRelatedDept(lblQuaInfoProNo.Text, user.department);
                        context.SaveChanges();
                        Response.Redirect("SubmitSuccess.aspx");
                    }
                }
            }
        }

        protected void btnRollback_Click(object sender, EventArgs e)
        {
            //从session中取出当前用户信息并显示
            CurUser user = (CurUser)Session["CurUser"];
            //判断当前用户是否具有归档权限
            bool roleAccess = Permission.JudgePermission(user, "2B", "B2");
            if (Request["close"].ToString().Equals("1"))  //闭环确认
            {
                if (roleAccess)
                {
                    using (QuaManSysEntities context = new QuaManSysEntities())
                    {
                        var query = context.OuterQualityInfo.Find(lblQuaInfoProNo.Text);
                        query.processingStatus = "处理";
                        context.SaveChanges();
                        //把责任部门和关注部门处理字段全部设置为0
                        var process = (from d in context.OuterResponsibleDepart.
                                     Where(no => no.qualityInfoId.Equals(lblQuaInfoProNo.Text))
                                       select d);
                        foreach (var item in process)
                        {
                            item.processed = 0;
                        }
                        context.SaveChanges();
                        Response.Redirect("SubmitSuccess.aspx");
                    }
                }
            }
            else if (Request["close"].ToString().Equals("2")) //归档确认
            {
                if (roleAccess)
                {
                    using (QuaManSysEntities context = new QuaManSysEntities())
                    {
                        var query = context.OuterQualityInfo.Find(lblQuaInfoProNo.Text);
                        query.processingStatus = "处理";
                        context.SaveChanges();
                        Response.Redirect("SubmitSuccess.aspx");
                    }
                }
            }
            else
            {
                if (roleAccess)
                {
                    using (var db = new QuaManSysEntities())
                    {
                        var query = (from p in db.OuterQualityInfo
                                     where p.qualityInfoId == lblQuaInfoProNo.Text
                                     select p).SingleOrDefault();
                        query.processingStatus = "分发";
                        db.SaveChanges();
                    }

                    Response.Redirect("SubmitSuccess.aspx");
                }
            }
        }


        #region 文件上传
        protected void fileUpload()
        {
            #region
            int cnt = Convert.ToInt16(hidden.Value.ToString());
            HtmlInputFile f = this.FileUploadD1;
            UpLoadFile(f.PostedFile);

            for (int i = 2; i <= cnt; i++)
            {
                HttpPostedFile f1 = Request.Files["FileUploadD" + i];
                UpLoadFile(f1);
            }
            #endregion
        }

        /// <summary>
        /// 文件上传。
        /// </summary>
        /// <param name="InputFile"></param>
        /// <param name="Path"></param>
        public string UpLoadFile(HttpPostedFile InputFile)
        {

            //判断有控件内容进入
            string b = "";
            string xdd = "";
            try
            {
                xdd = InputFile.FileName.ToString();//获取上传文件的名字
            }
            catch (Exception e)
            {
                return xdd;
            }
            if (xdd != "")
            {
                string path = "~/FileUploadCS/" + lblQuaInfoProNo.Text + "/";

                string PRICE_FJ_FJMC = "";
                string PRICE_FJ_FJHZ = "";
                string PRICE_FJ_PATH_SC = "";
                string PRICE_FJ_PATH_XZ = "";

                PRICE_FJ_PATH_XZ = path;
                //上传全路径包括文件名G:\\新建文件夹 (4)\\新建 文本文档.txt
                PRICE_FJ_PATH_SC = InputFile.FileName;
                //文件名包括后缀 新建 文本文档.txt"
                PRICE_FJ_FJMC = PRICE_FJ_PATH_SC.Substring(PRICE_FJ_PATH_SC.LastIndexOf("\\") + 1);
                ////
                //建立上传对象
                //
                HttpPostedFile postedFile = InputFile;
                //文件名包括后缀 新建 文本文档.txt"
                string fileName = System.IO.Path.GetFileName(postedFile.FileName);
                //文件后缀
                PRICE_FJ_FJHZ = System.IO.Path.GetExtension(fileName);


                string phyPath = HttpContext.Current.Request.MapPath(PRICE_FJ_PATH_XZ);//获取文件所在根目录
                //判断路径是否存在,若不存在则创建路径
                DirectoryInfo upDir = new DirectoryInfo(phyPath);
                if (!upDir.Exists)
                {
                    upDir.Create();
                }
                //
                //保存文件
                //
                try
                {
                    postedFile.SaveAs(phyPath + PRICE_FJ_FJMC);//文件保存
                    return b = phyPath;

                }
                catch
                {
                    throw new ApplicationException("上传失败!");
                }
                //返回上传文件的信息
            }

            return b;
        }
        #endregion
        #region
        protected void btn_xz_Click(object sender, EventArgs e)
        {


            string path = "~/FileUploadCS/" + lblQuaInfoProNo.Text + "/";
            string phyPath = HttpContext.Current.Request.MapPath(path);
            DirectoryInfo upDir = new DirectoryInfo(phyPath);
            if (!upDir.Exists)
            {
                Response.Write("<script>alert('附件不存在')</script>");
                return;
            }
            string wjm = Server.UrlEncode(phyPath);//要进行编码的转换
            //Page.RegisterStartupScript("", " <script   language=javascript> window.open   ( '附件下载.aspx?wjm=" + wjm + " ','下载界面',   'height=300,   width=400,    toolbar=no,   menubar=no,   scrollbars=no,   resizable=no,  location=no,   status=no ') </script> ");
            Page.ClientScript.RegisterStartupScript(GetType(), "", " <script   language=javascript> window.open   ( 'attatchDownload.aspx?wjm=" + wjm + " ','下载界面',   'height=300,   width=400,    toolbar=no,   menubar=no,   scrollbars=no,   resizable=no,  location=no,   status=no ') </script> ");

        }
        #endregion

        protected void initAttatchment()
        {
            string path = "~/FileUploadCS/" + lblQuaInfoProNo.Text + "/";
            string phyPath = HttpContext.Current.Request.MapPath(path);
            DirectoryInfo upDir = new DirectoryInfo(phyPath);
            if (!upDir.Exists)
            {
                return;
            }
            FileInfo[] fileInfo = upDir.GetFiles();
            attatch.DataSource = fileInfo;
            attatch.DataBind();

        }

        protected void OnItemCommand(object sender, RepeaterCommandEventArgs e)
        {

            string path = "~/FileUploadCS/" + lblQuaInfoProNo.Text + "/" + e.CommandArgument;
            string phyPath = HttpContext.Current.Request.MapPath(path);
            if (e.CommandName == "delete")
            {
                FileInfo file = new System.IO.FileInfo(phyPath);
                if (file.Exists)
                {
                    file.Delete();
                    foreach (RepeaterItem item in attatch.Items)
                    {
                        TextBox tb = (TextBox)item.FindControl("attatchName");
                        if (tb.Text == e.CommandArgument.ToString())
                        {
                            tb.Visible = false;
                            Button btn1 = (Button)item.FindControl("d1");
                            Button btn2 = (Button)item.FindControl("d2");
                            btn1.Visible = false;
                            btn2.Visible = false;
                        }
                    }
                }

            }
            else if (e.CommandName == "download")
            {
                FileInfo file = new System.IO.FileInfo(phyPath);
                Page.Response.Buffer = false;
                Page.Response.Charset = "UTF-8";
                Page.Response.AppendHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode((file.Name)));
                Page.Response.HeaderEncoding = System.Text.Encoding.UTF8;
                Page.Response.ContentEncoding = System.Text.Encoding.UTF8;//GetEncoding("UTF-8");
                Page.Response.ContentType = "application/ms-excel";
                Page.Response.WriteFile(file.FullName);
                //System.IO.File.Delete(file.FullName);
                Page.Response.End();
            }

        }
    }
}